package com.lnj.community.service.Impl;


import com.lnj.community.dao.entity.Comment;
import com.lnj.community.mapper.CommentMapper;
import com.lnj.community.service.CommentService;
import com.lnj.community.service.DiscussPostService;
import com.lnj.community.utiles.CommunityConstant;
import com.lnj.community.utiles.SensitiveUtile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService , CommunityConstant {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SensitiveUtile sensitiveUtile;
    @Autowired
    private DiscussPostService discussPostService;

    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @Override
    public int addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }
        //对评论内容继续过滤
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveUtile.filter(comment.getContent()));

        int rows = commentMapper.insertComment(comment);
        //更新帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }

        return 0;
    }

    @Override
    public Comment findCommentById(int entityId) {
        return commentMapper.selectCommentById(entityId);
    }

    @Override
    public List<Comment> findCommentByUserId(int userId) {
        return commentMapper.selectCommentByUserId(userId);
    }

    @Override
    public int findCommentCountByUserId(int userId) {
        return commentMapper.selectCountByUserId(userId);
    }

    @Override
    public int findCommentCount(int id) {
        return commentMapper.selectCountById(id);
    }

}
